package com.service.impl;

import com.POJO.GradeAdd;
import com.mapper.GradeMapper;
import com.POJO.Grade;
import com.service.GradeService;
import com.util.MybatisConfig;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * GradeServiceImpl是GradeService的具体实现类，
 * 提供对学生成绩的各种操作，如获取成绩、修改成绩等。
 */
@Service
public class GradeServiceImpl implements GradeService {
    private GradeMapper gradeMapper;
    private SqlSession sqlSession;

    private void openSession(){
        sqlSession = MybatisConfig.getSession();
        gradeMapper = sqlSession.getMapper(GradeMapper.class);
    }

    /**
     * 根据科目ID获取学生成绩
     * @param subjectId 科目ID
     * @return 学生成绩列表
     */
    @Override
    public List<Grade> getGradesBySubjectId(int subjectId) {
        openSession();
        try {
            return gradeMapper.getGradesBySubjectId(subjectId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 修改学生成绩
     * @param grade 成绩对象
     * @return 修改结果页面
     */
    @Override
    public String editGrade(Grade grade) {
        openSession();
        gradeMapper.updateGrade(grade.getGrade(), grade.getStudentId());
        sqlSession.commit();
        sqlSession.close();
        return "studentGrades";
    }

    /**
     * 根据学生ID获取学生的所有成绩
     * @param studentId 学生ID
     * @return 学生成绩列表
     */
    @Override
    public List<Grade> getGradesByStudentId(int studentId) {
        openSession();
        try {
            return gradeMapper.getGradesByStudentId(studentId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 新增学生成绩
     * @param grade 成绩对象
     */
    @Override
    public void addGrade(GradeAdd grade) {
        openSession();
        try {
            gradeMapper.insertGrade(grade);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}
